<template>
  <div class="panel-tab__content">
    <!--字段列表-->
    <div class="element-property list-property">
      <el-divider><i class="el-icon-coin"></i> 表单字段</el-divider>
      <el-radio-group class="radio-all" v-model="radioAll" @change="saveRadioAll($event)">
        <el-radio :label="'1'">全只读</el-radio>
        <el-radio :label="'2'">全禁用</el-radio>
        <el-radio :label="'3'">全必填</el-radio>
        <el-radio :label="'4'">全隐藏</el-radio>
        <el-radio :label="'5'">全可写</el-radio>
      </el-radio-group>

      <el-table :data="showJson" size="mini" max-height="300" border fit>
        <el-table-column  label="字段名称" prop="label"  width="80px"  show-overflow-tooltip />
        <el-table-column label="权限" width="330px">
          <template slot-scope="{ row }">
            <el-radio-group v-model="row.defaultValue"  @change="saveRadio(row)">
              <el-radio :label="'1'" style="width: 30px">只读</el-radio>
              <el-radio :label="'2'" style="width: 30px; margin-left: 0px" >禁用</el-radio>
              <el-radio :label="'3'" style="width: 30px; margin-left: 0px" >必填</el-radio>
              <el-radio :label="'4'" style="width: 30px; margin-left: 0px" >隐藏</el-radio>
              <el-radio :label="'5'" style="width: 30px; margin-left: 0px" >可写</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="element-property input-property" v-show="id.indexOf('Activity') !== -1">
      <div class="element-property__label" style="width: 150px; padding-right: 32px">发起者修改节点：</div>
      <div class="element-property__value" style="margin-left: -30px;">
        <el-switch
          v-model="rejectValue"
          active-text="是"
          inactive-text="否"
          @change="saveRejectVal"
        >
        </el-switch>
      </div>
    </div>
  </div>
</template>

<script>
import { getFormVersion } from "@/api/flowable/formVersion";
import { getBpmnConfig } from "@/api/flowable/front";
export default {
  name: "ElementForm",
  props: {
    id: String,
    type: String,
    formVersionId: String,
  },
  inject: {
    prefix: "prefix",
    width: "width",
  },
  data() {
    return {
      formKey: "",
      formList: [],
      businessKey: "",
      optionModelTitle: "",
      fieldList: [],
      formFieldForm: {},
      fieldType: {
        long: "长整型",
        string: "字符串",
        boolean: "布尔类",
        date: "日期类",
        enum: "枚举类",
        custom: "自定义类型",
      },
      formFieldIndex: -1, // 编辑中的字段， -1 为新增
      formFieldOptionIndex: -1, // 编辑中的字段配置项， -1 为新增
      fieldModelVisible: false,
      fieldOptionModelVisible: false,
      fieldOptionForm: {}, // 当前激活的字段配置项数据
      fieldOptionType: "", // 当前激活的字段配置项弹窗 类型
      fieldEnumList: [], // 枚举值列表
      fieldConstraintsList: [], // 约束条件列表
      fieldPropertiesList: [], // 绑定属性列表



      authMap: {},
      formFields: [],
      formContainers: [],
      jsonFieldList: [],
      jsonAll: {}, //存接口的数据
      showJson: [],
      rejectValue: false,
      rejectNode: '',
      radioAll:'0'
    };
  },
  watch: {
    id: {
      immediate: true,
      handler(val,oldval) {
        if(oldval)
          val && val.length && this.$nextTick(() => this.resetFormList());
      },
    },
  },
  created() {
    //add by yjc
    this.bpmnElement = window.bpmnInstances.bpmnElement;
    this.formKey = this.bpmnElement.businessObject.formKey;
    // 获取元素扩展属性 或者 创建扩展属性
    this.elExtensionElements =
      this.bpmnElement.businessObject.get("extensionElements") ||
      window.bpmnInstances.moddle.create("bpmn:ExtensionElements", {
        values: [],
      });
    this.formData =
      this.elExtensionElements.values.filter(
        (ex) => ex.$type === `${this.prefix}:FormData`
      )?.[0] ||
      window.bpmnInstances.moddle.create(`${this.prefix}:FormData`, {
        fields: [],
      });

    getFormVersion(this.formVersionId).then((res) => {
      this.formFields = JSON.parse(res.data.formField);
      this.formContainers = JSON.parse(res.data.formContainer);

      getBpmnConfig(this.$route.query.appVersionId).then((res) => {
        if (!!res.data) {
          if(!!res.data.nodeConfig){
            let tempObj = JSON.parse(res.data.nodeConfig);
            if(!!this.$store.state.bpmnNodeSettings.nodeConfig){
              tempObj = Object.assign(tempObj, this.$store.state.bpmnNodeSettings.nodeConfig)
            }
            this.$store.commit('bpmnNodeSettings/UPDATE_CONFIGNODE', tempObj)
          }
          if(res.data.rejectNode){
            this.$store.commit('bpmnNodeSettings/UPDATE_REJECTNODE', res.data.rejectNode)
            this.rejectNode = res.data.rejectNode;
            if (this.rejectNode !== null && this.rejectNode === this.id) {
              this.rejectValue = true;
            } else {
              this.rejectValue = false;
            }
          }
        }
        this.addFieldWhenChangeId();
      });
    });
  },
  methods: {
    addFieldWhenChangeId() {
      this.jsonFieldList = [];
      this.authMap = {};
      if(!this.formFields){
          return;
      }
      if(!!this.$store.state.bpmnNodeSettings.nodeConfig){
        this.jsonAll = this.$store.state.bpmnNodeSettings.nodeConfig;
      }
      if(!!this.$store.state.bpmnNodeSettings.rejectNode){
        this.rejectNode = this.$store.state.bpmnNodeSettings.rejectNode;
      }
      this.formContainers.forEach(element => {
        let value = '5';
        if(this.jsonAll[this.id] && this.jsonAll[this.id][element.name]){
          value = this.jsonAll[this.id][element.name];
        }
        this.jsonFieldList.push({
            label: element.label,
            field: element.name,
            defaultValue: value,
        });
        this.authMap[element.name] = value;
      })

      this.formFields.forEach(element => {
        let value = '5';
        if(this.jsonAll[this.id] && this.jsonAll[this.id][element.name]){
            value = this.jsonAll[this.id][element.name];
        }
        this.jsonFieldList.push({
          label: element.label,
          field: element.name,
          defaultValue: value,
        });
        this.authMap[element.name] = value;
      })

      this.jsonAll[this.id] = this.authMap;
      if (this.rejectNode !== null && this.rejectNode === this.id){
        this.rejectValue = true;
      } else {
        this.rejectValue = false;
      }
      this.showJson = this.jsonFieldList;

    },
    saveRadio(row) {
      this.jsonAll[this.id][row.field] = row.defaultValue;
      this.$store.commit('bpmnNodeSettings/UPDATE_CONFIGNODE', this.jsonAll)
    },

    saveRadioAll(event){
      for (const key in this.jsonAll[this.id]) {
        this.jsonAll[this.id][key] = event;
      }
      this.$store.commit("bpmnNodeSettings/UPDATE_CONFIGNODE", this.jsonAll);
      this.addFieldWhenChangeId()
    },
    saveRejectVal(val) {
      if(val) {
        this.$store.commit('bpmnNodeSettings/UPDATE_REJECTNODE', this.id)
        if(this.rejectNode === '')
          this.rejectNode = this.id
      }
    },
    resetFormList() {
      this.bpmnElement = window.bpmnInstances.bpmnElement;

      this.formKey = this.bpmnElement.businessObject.formKey;
      // 获取元素扩展属性 或者 创建扩展属性
      this.elExtensionElements =
        this.bpmnElement.businessObject.get("extensionElements") ||
        window.bpmnInstances.moddle.create("bpmn:ExtensionElements", {
          values: [],
        });
      // 获取元素表单配置 或者 创建新的表单配置
      this.formData =
        this.elExtensionElements.values.filter(
          (ex) => ex.$type === `${this.prefix}:FormData`
        )?.[0] ||
        window.bpmnInstances.moddle.create(`${this.prefix}:FormData`, {
          fields: [],
        });

      // 业务标识 businessKey， 绑定在 formData 中
      this.businessKey = this.formData.businessKey;

      // 保留剩余扩展元素，便于后面更新该元素对应属性
      this.otherExtensions = this.elExtensionElements.values.filter(
        (ex) => ex.$type !== `${this.prefix}:FormData`
      );

      // 复制原始值，填充表格
      this.fieldList = JSON.parse(JSON.stringify(this.formData.fields || []));

      this.addFieldWhenChangeId();
      this.radioAll = '0'
      // 更新元素扩展属性，避免后续报错
      this.updateElementExtensions();
    },
    updateElementFormKey() {
      window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
        formKey: this.formKey,
      });
    },
    updateElementBusinessKey() {
      window.bpmnInstances.modeling.updateModdleProperties(
        this.bpmnElement,
        this.formData,
        {
          businessKey: this.businessKey,
        }
      );
    },

    updateElementExtensions() {
      // 更新回扩展元素
      const newElExtensionElements = window.bpmnInstances.moddle.create(
        `bpmn:ExtensionElements`,
        {
          values: this.otherExtensions.concat(this.formData),
        }
      );
      // 更新到元素上
      window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
        extensionElements: newElExtensionElements,
      });
    }
  },
};
</script>
<style scoped>
.radio-all{
  margin: 10px 0px;
}
.radio-all .el-radio{
  margin-right: 4px !important;
}
</style>
